package cn.edu.just.firstjavaapp.l21;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Draw03Demo extends JPanel implements ActionListener {

    int x=10;
    int y=10;

    int deltaX = 1;
    int deltay = 2;
    MoveBall moveBall = new MoveBall();

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.RED);
        g.fillOval(x,y,20,20);
        System.out.println("paint is called");
    }



    public static void main(String[] args) {
        JFrame frame = new JFrame("我的画图");
        frame.setBounds(200,10,1000,600);
        Draw03Demo drawDemo = new Draw03Demo();
        drawDemo.setBackground(Color.white);
        frame.add(drawDemo,BorderLayout.CENTER);
        JButton change = new JButton("改变销量");
        change.addActionListener(drawDemo);
        frame.add(change,BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        moveBall.start();

    }

    class MoveBall extends Thread{
        public void run(){
            int n = 0;
            while(n<10000) {
                x = x + deltaX;
                if(x>500){
                    deltaX=-1;
                }
                if(x<0){
                    deltaX = 1;
                }
                y = y + deltay;
                if(y>500){
                    deltay = -2;
                }
                if(y<0){
                    deltay = 2;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                repaint();
            }
        }
    }
}
